package com.pro.springboot.controller;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pro.springboot.interfacep.YtVerdictLostInterface;
import com.pro.springboot.model.YtVerdictLostModel;

@RestController
public class HandleDataController {
	@Autowired
	private YtVerdictLostInterface ytVerdictLostInterface;

	@RequestMapping("/hello")
	public String hello() {
		System.out.println("启动成功!");
		return "hello world!";
	}

	/**
	 * 查询一条数据
	 * 
	 * @return
	 */
	@GetMapping(value = "/ytget")
	public YtVerdictLostModel getList() {
		return ytVerdictLostInterface.findOne(1531303587252L);
	}

	/**
	 * 查询一条数据
	 * 
	 * @return
	 */
	@GetMapping(value = "/ytget/{id}")
	public YtVerdictLostModel getById(@PathVariable("id") Long id) {
		return ytVerdictLostInterface.findOne(id);
	}

	/**
	 * 查询一条数据
	 * 
	 * @return
	 */
	@GetMapping(value = "/ytget/name")
	public List<YtVerdictLostModel> getByName(@RequestParam("name") String name) {
		jiexiCSV();
		return ytVerdictLostInterface.findByCompanyNameLike(name);
	}

	/**
	 * 分页查询数据
	 */
	// @GetMapping(value = "/ytget/name/page")
	// public Page<YtVerdictLostModel> getByName1() {
	// int page = 0, size = 10;
	// Sort sort = new Sort(Sort.Direction.DESC, "createTime");
	// Pageable pageable = new PageRequest(page, size, sort);
	// Page<YtVerdictLostModel> findAllYT =
	// ytVerdictLostInterface.findAll(pageable);
	// System.out.println(findAllYT.getTotalPages());
	// System.out.println(findAllYT.getTotalElements());
	// List<YtVerdictLostModel> aa = findAllYT.getContent();
	// for (YtVerdictLostModel u : aa) {
	// System.out.println(u.toString());
	// }
	// return findAllYT;
	// }

	/**
	 * 分页查询数据处理120w
	 * 
	 * @return
	 */
	@GetMapping(value = "/ytget/name/page")
	public Page<YtVerdictLostModel> chuLi() {
		try {
			int page = 0, size = 50;
			Sort sort = new Sort(Sort.Direction.DESC, "createTime");
			Pageable pageable = new PageRequest(page, size, sort);
			Page<YtVerdictLostModel> findAllYT = ytVerdictLostInterface.findAll(pageable);
			System.out.println(findAllYT.getTotalPages());// 总页数
			System.out.println(findAllYT.getTotalElements());// 总条数
			List<YtVerdictLostModel> aa = findAllYT.getContent();
			for (YtVerdictLostModel model : aa) {
				String uniqueCode = getUniqueCode(model.getCompanyName());
				if (uniqueCode == null) {
					fileChaseFW(model.getId() + "-" + model.getCompanyName() + ",");
				} else {
					model.setCreditCode(uniqueCode);
				}
			}
			ytVerdictLostInterface.save(findAllYT.getContent());
			System.out.println("50条结束,睡眠10秒");
			Thread.sleep(10000);
			for (int i = 1; i <= findAllYT.getTotalPages(); i++) {
				sort = new Sort(Sort.Direction.DESC, "createTime");
				pageable = new PageRequest(page, size, sort);
				findAllYT = ytVerdictLostInterface.findAll(pageable);
				aa = findAllYT.getContent();
				// 遍历查询数据，有统一社会信用代码存入数据库,没有的记录到文档
				for (YtVerdictLostModel model : aa) {
					String uniqueCode = getUniqueCode(model.getCompanyName());
					if (uniqueCode == null) {
						fileChaseFW(model.getId() + "-" + model.getCompanyName() + ",");
					} else {
						model.setCreditCode(uniqueCode);
					}
				}
				ytVerdictLostInterface.save(findAllYT.getContent());
				System.out.println((i + 1) * 50 + "条结束,睡眠10秒");
				Thread.sleep(10000);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Test
	public void jiexiCSV() {
		Long getN=0L;
		Long saveN=0L;
		Long noH=0L;
		BufferedReader br = null;
		try {
			DataInputStream in = new DataInputStream(new FileInputStream(new File("D:\\qiyeliebiao.txt")));
			br = new BufferedReader(new InputStreamReader(in, "utf-8"));
		} catch (FileNotFoundException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String line = "";
		String everyLine = "";
		try {
			while ((line = br.readLine()) != null) // 读取到的内容给line变量
			{
				everyLine = line;
				String[] split = everyLine.split(",");
				if(split.length>1) {
					if(split[1]!=null && !"".equals(split[1])) {
						List<YtVerdictLostModel> findByCompanyNameLike = ytVerdictLostInterface.findByCompanyNameLike(split[0]!=null?split[0]:"123");
						if(findByCompanyNameLike != null ) {
							for (YtVerdictLostModel ytVerdictLostModel : findByCompanyNameLike) {
								ytVerdictLostModel.setCreditCode(split[1]);
							}
							List<YtVerdictLostModel> save = ytVerdictLostInterface.save(findByCompanyNameLike);
							saveN+=save.size();
							getN+=findByCompanyNameLike.size();
							System.out.println("公司:"+split[0]+"   查询条数："+findByCompanyNameLike.size()+"   存入条数："+save.size());
							System.out.println("总查询数:"+getN+"   总存入数:"+saveN);
						}
					}else {
						fileChaseFW(split[0]+",");
						noH+=1;
					}
				}
			}
			System.out.println("无社会统一信用代码数量:"+noH);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入查询不到的公司
	 */
	public static void fileChaseFW(String content) {
		try {
			File file = new File("D:\\yupengCompany.txt");
			content = content + ",";
			// 构造函数中的第二个参数true表示以追加形式写文件
			FileWriter fw = new FileWriter("D:\\yupengCompany.txt", true);
			fw.write(content);
			fw.close();
		} catch (IOException e) {
			System.out.println("文件写入失败！" + e);
		}
	}

	/**
	 * 根据公司名称查询单位的代码
	 */
	// @GetMapping(value = "/ytget/namecha")
	public String getUniqueCode(String companyName) {
		// 获取请求连接
		Connection con = Jsoup
				.connect("http://www.creditchina.gov.cn/api/public_search/getCreditCodeFacades?keyword=" + companyName
						+ "&filterManageDept=0&filterOrgan=0&filterDivisionCode=0&page=1&pageSize=10&_=1533003101138");
		Document doc = null;
		try {
			doc = con.get();
			// 获取标题
			System.out.println(doc.text());
			JSONObject json = JSONObject.parseObject(doc.text());
			String status = json.getString("status");
			if (status.equals("1")) {
				String results = json.getString("results");
				JSONArray parse = JSONArray.parseArray(results);
				JSONObject object = parse.getJSONObject(0);
				String string = object.getString("creditCode");
				return string;
			} else {
				return null;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return companyName;

	}

	public static void main(String[] args) {
		String ss = "{\"message\":\"成功\",\"status\":1,\"results\":[{\"entname\":\"蓬莱龢力商贸有限公司\",\"creditCode\":\"91370684326176524K\",\"taxCode\":\"\",\"regCode\":\"370684200026448\",\"organizationCode\":\"\",\"modifyTime\":1533005105196}],\"page\":1,\"pageSize\":10,\"totleNumber\":1}";
		JSONObject json = JSONObject.parseObject(ss);
		String status = json.getString("status");
		if (status.equals("1")) {
			String results = json.getString("results");
			JSONArray parse = JSONArray.parseArray(results);
			JSONObject object = parse.getJSONObject(0);
			String string = object.getString("entname");
			System.out.println(string);
		} else {

		}
	}

}
